
package todolist.util;

import java.util.ArrayList;
import java.util.ListIterator;

/**
 * Format data according to fields of specified lengths.
 * @author Ivan
 */
public class FieldFormatter {

	private ArrayList<String> _objFieldList;
	private ArrayList<Integer> _objLengthList;
	
	public FieldFormatter() {
		_objFieldList = new ArrayList<String>();
		_objLengthList = new ArrayList<Integer>();
	}
	
	/**
	 * Adds data and length to pad with. Does not actually format data till toString is called.
	 */
	public void addField(String pstrFieldData, int pintLength) throws IllegalArgumentException {
		if (pstrFieldData == null)
			throw new IllegalArgumentException("FieldFormatter.addField(): Field data cannot be null.");
		if (pintLength <= 0)
			throw new IllegalArgumentException("FieldFormatter.addField(): Field length must be a positive number.");
		_objFieldList.add(pstrFieldData);
		_objLengthList.add(new Integer(pintLength));
	}
	
	@Override
	public String toString() {
		assert _objFieldList.size() == _objLengthList.size();
		StringBuffer objSB = new StringBuffer();
		ListIterator<String> objFieldItr = _objFieldList.listIterator();
		ListIterator<Integer> objLengthItr = _objLengthList.listIterator();
		int intTotalFieldLength = 0;
		while (objFieldItr.hasNext()) {
			objSB.append(objFieldItr.next());
			intTotalFieldLength += objLengthItr.next().intValue();
			if (intTotalFieldLength <= objSB.length())
				continue;
			// some space remaining to be padded
			int intNumOfSpaces = intTotalFieldLength - objSB.length();
			while (intNumOfSpaces-- > 0)
				objSB.append(" ");
		}
		return objSB.toString();
	}
	
}
